/**
 * @description 一行展示的两个input模板
 * @example 重仓行业变化（申万）
 * @author gf
 */

import { Fragment, useEffect, useState } from "react";
import { FlexDiv, Box, Text } from "./SelectInput";
import { RedBtn } from "../Button";
import { BottomCard } from "./BottomCard";
import { RedTitle } from "../Title/redTitile";
import SInputNumber from "../Input/InputNumber";
import { ToFixNumber } from "@/utils/utils";

export const collectErrors = (
  val?: string,
  key?: string,
  errorList = [],
  saveParams = {}
) => {
  let res: string[] = errorList;
  if (key) {
    val
      ? (res = errorList.filter((v) => v !== key))
      : (res = errorList.concat([key]));
  } else {
    for (let key of Object.keys(saveParams)) {
      if (key === "benchmarkCode" && !saveParams[key]) {
        res.push(key);
      } else if (
        key !== "benchmarkCode" &&
        !saveParams[key] &&
        Number(saveParams[key]) !== Number(saveParams[key])
      ) {
        res.push(key);
      }
    }
  }
  return res;
};

const Positive = [
  "deviation_from_benchmark_fundtype_positive", // 与同类型正偏移
  "deviation_from_benchmark_style_positive", // 与风格指数正偏移
];
const Negative = [
  "deviation_from_benchmark_fundtype_negative", // 与同类型负偏移
  "deviation_from_benchmark_style_negative", // 与风格指数负偏移
];

// 适合此模板的事件代码
export const EVENT_INLINE_INPUT = [
  "heavy_holding_industry_alert_sw", // 重仓行业变化（申万）
  "heavy_holding_industry_alert_quarterly", // 重仓行业变化（季度披露）
  "heavy_holding_industry_alert_zz", // 重仓行业变化（中证）
  "heavy_holding_industry_alert_predicted", //重仓行业变化（预测）
  "deviation_from_benchmark_fundtype", // 与同类型偏移
  "deviation_from_benchmark_style", // 与风格指数偏移
  ...Positive,
  ...Negative
];

const INPUT_HEAVY = [
  // 适合重仓形式的事件，第一个input框的取值字段是 heavyIndustry
  "heavy_holding_industry_alert_sw",
  "heavy_holding_industry_alert_quarterly",
  "heavy_holding_industry_alert_zz",
  "heavy_holding_industry_alert_predicted",
];

const PLACEHOLDER_1 = {
  // 第一部分文本
  heavy_holding_industry_alert_sw: "定期报告过去4期第一大重仓申万行业平均仓位>",
  heavy_holding_industry_alert_quarterly:
    "季度定期报告过去4期第一大重仓行业平均仓位>",
  heavy_holding_industry_alert_zz: "定期报告过去4期第一大重仓中证行业平均仓位>",
  heavy_holding_industry_alert_predicted: "根据基金股票仓位预测重仓行业占比>",
  deviation_from_benchmark_fundtype: "基金近",
  deviation_from_benchmark_style: "基金近",
  deviation_from_benchmark_fundtype_positive: "基金近",
  deviation_from_benchmark_fundtype_negative: "基金近",
  deviation_from_benchmark_style_negative: '基金近',
  deviation_from_benchmark_style_positive: '基金近'
};

const PLACEHOLDER_2 = {
  // 第二部分文本
  heavy_holding_industry_alert_sw: "%，且变化",
  heavy_holding_industry_alert_quarterly: "%，且变化",
  heavy_holding_industry_alert_zz: "%，且变化",
  heavy_holding_industry_alert_predicted: "%，且变化",
  deviation_from_benchmark_fundtype: "日 与中证基金指数相比超额收益率<",
  deviation_from_benchmark_style: "日 与风格指数相比超额收益率<",
  deviation_from_benchmark_fundtype_positive: "日 与中证基金指数相比超额收益率≥",
  deviation_from_benchmark_fundtype_negative: "日 与中证基金指数相比超额收益率≤",
  deviation_from_benchmark_style_negative: '日 与风格指数相比超额收益率≤',
  deviation_from_benchmark_style_positive: '日 与风格指数相比超额收益率≥'
};

const PLACEHOLDER_3 = {
  // 第三部分文本
  heavy_holding_industry_alert_sw: "%以上",
  heavy_holding_industry_alert_quarterly: "%以上",
  heavy_holding_industry_alert_zz: "%以上",
  heavy_holding_industry_alert_predicted: "%以上",
  deviation_from_benchmark_fundtype: "%",
  deviation_from_benchmark_fundtype_positive: "%",
  deviation_from_benchmark_fundtype_negative: "%",
  deviation_from_benchmark_style: "%",
  deviation_from_benchmark_style_negative: '%',
  deviation_from_benchmark_style_positive: '%'
};

const UNIT_LIST = [
  // 所有事件的单位全集
  "%",
  "日",
  "年",
];

const UNIQUE_TEXT = [
  "deviation_from_benchmark_fundtype",
  "deviation_from_benchmark_style",
  ...Negative,
  ...Positive
];

/**
 *
 * @param content : 文案内容;
 * @returns str 返回匹配的单位
 */
export const IsExitUnit = (content: string, list: string[]) => {
  // 判断文案是否包含单位
  let str = "";
  list.map((v) => {
    if (content.indexOf(v) > -1) {
      str = v;
    }
  });
  return str;
};

// 与后端对应的字段不同
// 重仓行业

const InlineInput = (props: any) => {
  const { thresholdValue, onSubmit, eventInfo, enable } = props;
  const [saveParams, setSaveParams] = useState({
    gapDay: "",
    threshold: "",
    heavyIndustry: "",
  });
  const [isChanged, setIsChanged] = useState(false);
  const [errorList, setErrorList] = useState([]);

  useEffect(() => {
    setSaveParams({
      gapDay: thresholdValue?.gapDay,
      threshold: thresholdValue?.threshold,
      heavyIndustry: thresholdValue?.heavyIndustry,
    });
    setIsChanged(false);
    setErrorList([]);
  }, [thresholdValue]);

  const onChange = (val: string | number | null, key: string) => {
    handleCollectErrors(val?.toString(), key);
    setIsChanged(true);
    setSaveParams((state) => {
      return {
        ...state,
        [key]: val,
      };
    });
  };

  // 收集错误
  const handleCollectErrors = (val?: string, key?: string) => {
    let res = collectErrors(val, key, errorList, saveParams);
    res = res.filter((v) =>
      INPUT_HEAVY.includes(eventInfo.value)
        ? v !== "gapDay"
        : v !== "heavyIndustry"
    );
    console.log(res);

    setErrorList([...new Set(res)]);
    return [...new Set(res)];
  };

  useEffect(() => {
    if (enable !== undefined && enable !== eventInfo?.enable) {
      setIsChanged(true);
    }
  }, [enable]);

  const onClick = () => {
    const res = handleCollectErrors();
    console.log(res, errorList);

    if (res.length > 0) return;
    onSubmit({
      id: parseFloat(eventInfo.key),
      preValue: saveParams,
      dataMemo: createText(false),
    });
  };

  const createText = (html: Boolean) => {
    // 创建文案
    let str = `<p>
    * ${PLACEHOLDER_1[eventInfo.value]}
    <em>
      ${
        INPUT_HEAVY.includes(eventInfo.value)
          ? ToFixNumber(saveParams.heavyIndustry)
          : ToFixNumber(saveParams.gapDay)
      }${IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST)}
    </em>
    ${PLACEHOLDER_2[eventInfo.value].replace(
      IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST),
      ""
    )}
    <em>
      ${ToFixNumber(saveParams.threshold)}${IsExitUnit(
      PLACEHOLDER_3[eventInfo.value],
      UNIT_LIST
    )}
    </em>
    ${PLACEHOLDER_3[eventInfo.value].replace(
      IsExitUnit(PLACEHOLDER_3[eventInfo.value], UNIT_LIST),
      ""
    )} 。
  </p>`;
    if (!html) {
      str = str
        .replaceAll("<p>", "")
        .replaceAll("</p>", "")
        .replaceAll("<em>", "")
        .replaceAll("</em>", "")
        .replaceAll("\n", "")
        .replaceAll(" ", "");
    }
    return str;
  };

  console.log(eventInfo);

  return (
    <Fragment>
      <Box>
        <FlexDiv>
          <Text>{UNIQUE_TEXT.includes(eventInfo?.value) ? '近' : PLACEHOLDER_1[eventInfo.value]}</Text>
          <SInputNumber
            value={
              INPUT_HEAVY.includes(eventInfo.value)
                ? saveParams.heavyIndustry
                : saveParams.gapDay
            }
            isError={errorList.includes(
              INPUT_HEAVY.includes(eventInfo.value) ? "heavyIndustry" : "gapDay"
            )}
            onChange={(e) =>
              onChange(
                e,
                INPUT_HEAVY.includes(eventInfo.value)
                  ? "heavyIndustry"
                  : "gapDay"
              )
            }
            min={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "日"
                ? 0
                : -100
            }
            max={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "日"
                ? 1000
                : 100
            }
            precision={
              IsExitUnit(PLACEHOLDER_2[eventInfo.value], UNIT_LIST) === "日"
                ? 0
                : 2
            }
          />
          <Text>
            {UNIQUE_TEXT.includes(eventInfo?.value)
              ? `${Negative.includes(eventInfo?.value) ? '日超额收益率≤' : '日超额收益率≥'}`
              : PLACEHOLDER_2[eventInfo.value]}
          </Text>
          <SInputNumber
            value={saveParams.threshold}
            isError={errorList.includes("threshold")}
            onChange={(e) => onChange(e, "threshold")}
            min={
              UNIQUE_TEXT.includes(eventInfo?.value)
                ? -9999.999999
                : IsExitUnit(PLACEHOLDER_3[eventInfo.value], UNIT_LIST) === "日"
                ? 0
                : -100
            }
            max={
              UNIQUE_TEXT.includes(eventInfo?.value)
                ? 9999.999999
                : IsExitUnit(PLACEHOLDER_3[eventInfo.value], UNIT_LIST) === "日"
                ? 1000
                : 100
            }
            precision={
              UNIQUE_TEXT.includes(eventInfo?.value)
                ? 6
                : IsExitUnit(PLACEHOLDER_3[eventInfo.value], UNIT_LIST) === "日"
                ? 0
                : 2
            }
          />
          <Text>{PLACEHOLDER_3[eventInfo.value]}</Text>
        </FlexDiv>
        <BottomCard info={createText(true)} />
      </Box>
      <FlexDiv style={{ marginTop: 12, alignItems: "flex-end" }}>
        <RedBtn disabled={!isChanged} onClick={!isChanged ? null : onClick}>
          确定
        </RedBtn>
        {/* 按钮说明文案 */}
        {isChanged && <RedTitle eventInfo={eventInfo} />}
      </FlexDiv>
    </Fragment>
  );
};

export default InlineInput;
